import { useState, useCallback } from 'react'
import { Alert } from 'react-native'
import { RegisterApi, RegisterVO, ReasonFormApi, RegisterFileApi, RegisterFileVO, RegisterFileUpdateVO } from '../../../api/leave'
import { useLeaveDict } from '../../../hooks/useDict'
import { DICT_TYPE } from '../../../api/dict'
import AsyncStorage from '@react-native-async-storage/async-storage'

interface UseLeaveSubmissionProps {
    selectedReasons: (string | number)[]
    startDate: string
    endDate: string
    mainLeaveData?: {
        level?: number
        destinations?: string[]
        workArrangement?: string
        remark?: string
        hostId?: string
        personId?: string
        personAdmitId?: string
        deptId?: string
        uploadedImages?: any[] // 添加上传的图片数据
    }
    onSave: (reasonData: any) => void
    isEditMode?: boolean // 是否为编辑模式
    editData?: {
        registerId?: number // 编辑模式下的请假登记ID
        existingFiles?: any[] // 编辑模式下已存在的附件
    }
    deletedItems?: {
        researchItems: string[]
        trainingItems: string[]
        businessItems: string[]
        personalItems: string[]
        academicItems: string[]
        otherItems: string[]
    }
}

export const useLeaveSubmission = ({
    selectedReasons,
    startDate,
    endDate,
    mainLeaveData,
    onSave,
    isEditMode = false,
    editData
}: UseLeaveSubmissionProps) => {
    const [isSubmitting, setIsSubmitting] = useState(false)
    const { getDictOptions } = useLeaveDict()

    // 生成存储键名
    const getStorageKey = useCallback(() => {
        const reasonTypes = selectedReasons.sort().join('_')
        return `leave_reason_detail_${reasonTypes}_${startDate}_${endDate}`
    }, [selectedReasons, startDate, endDate])

    // 保存数据到AsyncStorage
    const saveDataToStorage = useCallback(async (data: any) => {
        try {
            const storageKey = getStorageKey()
            await AsyncStorage.setItem(storageKey, JSON.stringify(data))
        } catch (error) {
            console.error('保存数据到本地存储失败:', error)
        }
    }, [getStorageKey])

    // 验证表单数据
    const validateFormData = useCallback((formData: any) => {
        // 验证是否有填写内容
        const hasContent = Object.values(formData).some(items => 
            Array.isArray(items) && items.length > 0 && 
            items.some(item => Object.values(item).some(value => value && value !== ''))
        )

        if (!hasContent) {
            Alert.alert('提示', '请至少填写一项请假事由的详细信息')
            return false
        }

        // 验证必填字段
        const validationErrors: string[] = []
        
        // 检查调研事由
        if (formData.researchItems?.length > 0) {
            formData.researchItems.forEach((item: any, index: number) => {
                if (!item.theme || !item.theme.trim()) {
                    validationErrors.push(`调研事由第${index + 1}项：调研主题不能为空`)
                }
                if (!item.purpose || !item.purpose.trim()) {
                    validationErrors.push(`调研事由第${index + 1}项：调研目的不能为空`)
                }
                if (!item.organization || !item.organization.trim()) {
                    validationErrors.push(`调研事由第${index + 1}项：调研单位不能为空`)
                }
            })
        }
        
        // 检查培训事由
        if (formData.trainingItems?.length > 0) {
            formData.trainingItems.forEach((item: any, index: number) => {
                if (!item.theme || !item.theme.trim()) {
                    validationErrors.push(`培训事由第${index + 1}项：培训主题不能为空`)
                }
                if (!item.organization || !item.organization.trim()) {
                    validationErrors.push(`培训事由第${index + 1}项：培训单位不能为空`)
                }
            })
        }
        
        // 检查公务事由
        if (formData.businessItems?.length > 0) {
            formData.businessItems.forEach((item: any, index: number) => {
                if (!item.meetingName || !item.meetingName.trim()) {
                    validationErrors.push(`公务事由第${index + 1}项：会议名称不能为空`)
                }
                if (!item.organization || !item.organization.trim()) {
                    validationErrors.push(`公务事由第${index + 1}项：主办单位不能为空`)
                }
            })
        }
        
        // 检查因私事由
        if (formData.personalItems?.length > 0) {
            formData.personalItems.forEach((item: any, index: number) => {
                if (!item.type || !item.type.trim()) {
                    validationErrors.push(`因私事由第${index + 1}项：请假类型不能为空`)
                }
                if (!item.details || !item.details.trim()) {
                    validationErrors.push(`因私事由第${index + 1}项：请假详情不能为空`)
                }
                if (!item.phone || !item.phone.trim()) {
                    validationErrors.push(`因私事由第${index + 1}项：联系电话不能为空`)
                }
                // 验证手机号格式
                if (item.phone && item.phone.trim()) {
                    const phoneRegex = /^1[3-9]\d{9}$/
                    if (!phoneRegex.test(item.phone.trim())) {
                        validationErrors.push(`因私事由第${index + 1}项：请输入正确的11位手机号码`)
                    }
                }
                
                // 产假相关字段校验
                if (item.type === '产假' || item.type === '11') {
                    console.log(`检测到产假，开始校验相关字段`)
                    if (!item.parity || item.parity.trim() === '') {
                        validationErrors.push(`因私事由第${index + 1}项：生育次数不能为空`)
                    }
                    if (!item.multiple || item.multiple.trim() === '') {
                        validationErrors.push(`因私事由第${index + 1}项：是否多胞胎不能为空`)
                    }
                    if (!item.dystocia || item.dystocia.trim() === '') {
                        validationErrors.push(`因私事由第${index + 1}项：是否难产不能为空`)
                    }
                }

                // 探亲假相关字段校验
                if (item.type === '探亲假' || item.type === '6') {
                    if (!item.route || !item.route.trim()) {
                        validationErrors.push(`因私事由第${index + 1}项：探亲路线不能为空`)
                    }
                    if (!item.relation || !item.relation.trim()) {
                        validationErrors.push(`因私事由第${index + 1}项：探亲关系不能为空`)
                    }
                    if (!item.visitName || !item.visitName.trim()) {
                        validationErrors.push(`因私事由第${index + 1}项：探亲对象姓名不能为空`)
                    }
                    if (!item.visitType || !item.visitType.trim()) {
                        validationErrors.push(`因私事由第${index + 1}项：探亲类别不能为空`)
                    }
                    if (!item.visitAddress || !item.visitAddress.trim()) {
                        validationErrors.push(`因私事由第${index + 1}项：探亲地址不能为空`)
                    }
                    if (!item.maritalStatus || !item.maritalStatus.trim()) {
                        validationErrors.push(`因私事由第${index + 1}项：婚姻状况不能为空`)
                    }
                }
            })
        }
        
        // 检查学术事由
        if (formData.academicItems?.length > 0) {
            formData.academicItems.forEach((item: any, index: number) => {
                if (!item.meetingName || !item.meetingName.trim()) {
                    validationErrors.push(`学术事由第${index + 1}项：会议名称不能为空`)
                }
                if (!item.organizer || !item.organizer.trim()) {
                    validationErrors.push(`学术事由第${index + 1}项：主办方不能为空`)
                }
                // 如果有报告，则报告题目必填
                if (item.hasReport === '1' && (!item.reportTitle || !item.reportTitle.trim())) {
                    validationErrors.push(`学术事由第${index + 1}项：有报告时报告题目不能为空`)
                }
            })
        }
        
        // 检查其他事由
        if (formData.otherItems?.length > 0) {
            formData.otherItems.forEach((item: any) => {
                if (!item.description || !item.description.trim()) {
                    validationErrors.push(`其他事由项：事由描述不能为空`)
                }
            })
        }
        
        if (validationErrors.length > 0) {
            Alert.alert('验证失败', `请完善以下信息：\n\n${validationErrors.join('\n')}`)
            return false
        }

        return true
    }, [])

    // 提交请假申请
    const submitLeaveApplication = useCallback(async (formData: any) => {
        try {
            setIsSubmitting(true)
            
            // 验证主表单数据
            if (!startDate || !startDate.trim()) {
                Alert.alert('提示', '请选择开始日期')
                return false
            }
            
            if (!endDate || !endDate.trim()) {
                Alert.alert('提示', '请选择结束日期')
                return false
            }
            
            // 验证日期逻辑
            const start = new Date(startDate)
            const end = new Date(endDate)
            if (start > end) {
                Alert.alert('提示', '开始日期不能晚于结束日期')
                return false
            }
            
            // 验证前往地点
            if (!mainLeaveData?.destinations || mainLeaveData.destinations.length === 0) {
                Alert.alert('提示', '请至少填写一个前往地点')
                return false
            }
            
            // 验证前往地点不能为空或只包含空格
            const hasValidDestination = mainLeaveData.destinations.some(destination => 
                destination && destination.trim() !== ''
            )
            if (!hasValidDestination) {
                Alert.alert('提示', '前往地点不能为空，请填写有效的前往地点')
                return false
            }
            
            // 工作安排检验
            if (mainLeaveData?.level && Number(mainLeaveData.level) >= 27 && Number(mainLeaveData.level) !== 100) {
                if (!mainLeaveData?.workArrangement || !mainLeaveData.workArrangement.trim()) {
                    Alert.alert('提示', '请填写请假期间主持工作负责人安排')
                    return false
                }
            }
            
            if (mainLeaveData?.level && Number(mainLeaveData.level) >= 27 && Number(mainLeaveData.level) !== 100) {
                if (!mainLeaveData?.personAdmitId || !mainLeaveData.personAdmitId.trim()) {
                    Alert.alert('提示', '请选择代工人')
                    return false
                }
            } else {
                if (!mainLeaveData?.hostId || !mainLeaveData.hostId.trim()) {
                    Alert.alert('提示', '请选择单位负责人')
                    return false
                }
            }
            
            // 验证事由表单数据
            if (!validateFormData(formData)) {
                return false
            }
            
            if (isEditMode && formData.deletedItems) {
                
                // 删除调研事由
                for (const itemId of formData.deletedItems.researchItems) {
                    try {
                        const numericId = Number(itemId)
                        if (isNaN(numericId)) {
                            console.error('无效的调研事由ID:', itemId)
                            continue
                        }
                        await ReasonFormApi.deleteReasonForm(numericId)
                    } catch (error) {
                        console.error('删除调研事由失败:', itemId, error)
                    }
                }
                
                // 删除培训事由
                for (const itemId of formData.deletedItems.trainingItems) {
                    try {
                        await ReasonFormApi.deleteReasonForm(Number(itemId))
                    } catch (error) {
                        console.error('删除培训事由失败:', itemId, error)
                    }
                }
                
                // 删除公务事由
                for (const itemId of formData.deletedItems.businessItems) {
                    try {
                        await ReasonFormApi.deleteReasonForm(Number(itemId))
                    } catch (error) {
                        console.error('删除公务事由失败:', itemId, error)
                    }
                }
                
                // 删除因私事由
                for (const itemId of formData.deletedItems.personalItems) {
                    try {
                        await ReasonFormApi.deleteReasonForm(Number(itemId))
                    } catch (error) {
                        console.error('删除因私事由失败:', itemId, error)
                    }
                }
                
                // 删除学术会议事由
                for (const itemId of formData.deletedItems.academicItems) {
                    try {
                        await ReasonFormApi.deleteReasonForm(Number(itemId))
                    } catch (error) {
                        console.error('删除学术会议事由失败:', itemId, error)
                    }
                }
                
                // 删除其他事由
                for (const itemId of formData.deletedItems.otherItems) {
                    try {
                        await ReasonFormApi.deleteReasonForm(Number(itemId))
                    } catch (error) {
                        console.error('删除其他事由失败:', itemId, error)
                    }
                }
            }
            
            // 1. 先保存到本地存储
            await saveDataToStorage(formData)

            // 2. 调用父组件的回调函数，传递保存的数据
            onSave(formData)

            // 构建主申请数据
            const reasonsText = selectedReasons.map(type => {
                const option = getDictOptions(DICT_TYPE.LEAVE_TYPE).find(opt => opt.value === type)
                return option?.label || ''
            }).join('、')

            const leaveData: RegisterVO = {
                startDate: startDate ? `${startDate} 00:00:00` : undefined,
                endDate: endDate ? `${endDate} 00:00:00` : undefined,
                reasons: reasonsText,
                destination: mainLeaveData?.destinations?.join('|||') || '',
                hostArrangement: mainLeaveData?.workArrangement || '',
                remark: mainLeaveData?.remark || '',
                hostId: mainLeaveData?.hostId || '',
                personId: mainLeaveData?.personId ? Number(mainLeaveData.personId) : undefined,
                personAdmitId: mainLeaveData?.personAdmitId || '',
                deptId: mainLeaveData?.deptId ? Number(mainLeaveData.deptId) : undefined,
                leaderOpinion: '',
            }

            let leaveRegisterId: number
            
            if (isEditMode && editData?.registerId) {
                // 编辑模式：更新主请假申请
                leaveData.id = editData.registerId
                const response = await RegisterApi.updateRegister(leaveData)
                
                if (response && response.code !== 0) {
                    throw new Error(response.msg || '更新请假申请失败')
                }
                
                leaveRegisterId = editData.registerId
            } else {
                // 新增模式：创建主请假申请
                const response = await RegisterApi.createRegister(leaveData)
                
                if (response && response.code !== 0) {
                    throw new Error(response.msg || '创建请假申请失败')
                }

                // 获取 leaveRegisterId
                if (response && response.data) {
                    const id = Number(response.data)
                    if (isNaN(id)) {
                        throw new Error('无效的请假登记ID')
                    }
                    leaveRegisterId = id
                } else if (response && typeof response === 'number') {
                    leaveRegisterId = response
                } else {
                    throw new Error('无法获取请假登记ID')
                }
            }

            // 处理图片附件
            if (mainLeaveData?.uploadedImages && mainLeaveData.uploadedImages.length > 0) {
                try {
                    for (const image of mainLeaveData.uploadedImages) {
                        if (!image.url || image.url === image.uri) {
                            continue
                        }
                        
                        if (isEditMode && image.id) {
                            // 编辑模式：检查ID格式，时间戳格式说明是新上传的附件
                            if (typeof image.id === 'string' && image.id.includes('_')) {
                                // 新上传附件：创建新记录
                                const fileData: RegisterFileVO = {
                                    leaveRegisterId: leaveRegisterId,
                                    leaveFileUrl: image.url,
                                    leaveFileName: image.name,
                                    leaveFileSize: image.size || 0
                                }
                                
                                const fileResponse = await RegisterFileApi.createRegisterFile(fileData)
                                if (fileResponse && fileResponse.code !== 0) {
                                    console.error('附件记录创建失败:', image.name, fileResponse?.msg)
                                }
                            } else {
                                // 已存在附件：更新现有记录
                                const fileId = Number(image.id)
                                if (!isNaN(fileId)) {
                                    const fileData: RegisterFileUpdateVO = {
                                        id: fileId,
                                        leaveRegisterId: leaveRegisterId,
                                        leaveFileUrl: image.url,
                                        leaveFileName: image.name,
                                        leaveFileSize: image.size || 0
                                    }
                                    
                                    const fileResponse = await RegisterFileApi.updateRegisterFile(fileData)
                                    if (fileResponse && fileResponse.code !== 0) {
                                        console.error('附件记录更新失败:', image.name, fileResponse?.msg)
                                    }
                                }
                            }
                        } else {
                            const fileData: RegisterFileVO = {
                                leaveRegisterId: leaveRegisterId,
                                leaveFileUrl: image.url,
                                leaveFileName: image.name,
                                leaveFileSize: image.size || 0
                            }
                            
                            const fileResponse = await RegisterFileApi.createRegisterFile(fileData)
                            if (fileResponse && fileResponse.code === 0) {
                                console.log('图片附件记录创建成功:', image.name)
                            } else {
                                console.error('图片附件记录创建失败:', image.name, fileResponse?.msg)
                                throw new Error(`图片 ${image.name} 附件记录创建失败: ${fileResponse?.msg}`)
                            }
                        }
                    }
                } catch (attachmentError) {
                    console.error('附件处理失败:', attachmentError)
                    Alert.alert(
                        '附件处理失败',
                        '部分附件处理失败，是否继续提交请假申请？',
                        [
                            { text: '取消', style: 'cancel' },
                            { 
                                text: '继续提交', 
                                onPress: () => {}
                            }
                        ]
                    )
                    return false
                }
            }

            // 提交请假事由的详细信息
            if (formData && leaveRegisterId) {
                // 处理调研事由
                if (formData.researchItems?.length > 0) {
                    for (const research of formData.researchItems) {
                        if (research.theme && research.purpose && research.organization) {
                            const reasonFormData = {
                                id: research.id || "",
                                leaveRegisterId: leaveRegisterId,
                                type: 1, // 调研事由
                                startDate: research.startDate ? `${research.startDate} 00:00:00` : `${startDate} 00:00:00`,
                                endDate: research.endDate ? `${research.endDate} 00:00:00` : `${endDate} 00:00:00`,
                                subject: research.theme, 
                                purpose: research.purpose,
                                unit: research.organization, 
                            }
                            if (isEditMode && research.id !== undefined && research.id !== "") {
                                await ReasonFormApi.updateReasonForm(reasonFormData)
                            } else {
                                await ReasonFormApi.createReasonForm(reasonFormData)
                            }
                        }
                    }
                }

                // 处理培训事由
                if (formData.trainingItems?.length > 0) {
                    for (const training of formData.trainingItems) {
                        if (training.theme && training.organization) {
                            const reasonFormData = {
                                id: training.id || "",
                                leaveRegisterId: leaveRegisterId,
                                type: 2, // 培训事由
                                startDate: training.startDate ? `${training.startDate} 00:00:00` : `${startDate} 00:00:00`,
                                endDate: training.endDate ? `${training.endDate} 00:00:00` : `${endDate} 00:00:00`,
                                subject: training.theme, 
                                unit: training.organization, 
                            }
                            if (isEditMode && training.id !== undefined && training.id !== "") {
                                await ReasonFormApi.updateReasonForm(reasonFormData)
                            } else {
                                await ReasonFormApi.createReasonForm(reasonFormData)
                            }
                        }
                    }
                }

                // 处理公务事由
                if (formData.businessItems?.length > 0) {
                    for (const business of formData.businessItems) {
                        if (business.meetingName && business.organization) {
                            const reasonFormData = {
                                id: business.id || "",
                                leaveRegisterId: leaveRegisterId,
                                type: 3, // 公务事由
                                startDate: business.startDate ? `${business.startDate} 00:00:00` : `${startDate} 00:00:00`,
                                endDate: business.endDate ? `${business.endDate} 00:00:00` : `${endDate} 00:00:00`,
                                subject: business.meetingName, 
                                unit: business.organization, 
                            }
                            if (isEditMode && business.id !== undefined && business.id !== "") {
                                await ReasonFormApi.updateReasonForm(reasonFormData)
                            } else {
                                await ReasonFormApi.createReasonForm(reasonFormData)
                            }
                        }
                    }
                }

                // 处理因私事由
                if (formData.personalItems?.length > 0) {
                    for (const personal of formData.personalItems) {
                        if (personal.type && personal.details && personal.phone) {
                            // 计算总计天数
                            let totalDays = 0
                            if (personal.startDate && personal.endDate) {
                                const personalStartDate = new Date(personal.startDate)
                                const personalEndDate = new Date(personal.endDate)
                                const diffTime = Math.abs(personalEndDate.getTime() - personalStartDate.getTime())
                                totalDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)) + 1
                            }
                            
                            const reasonFormData = {
                                id: personal.id || "",
                                leaveRegisterId: leaveRegisterId,
                                type: 4, // 因私事由
                                startDate: personal.startDate ? `${personal.startDate} 00:00:00` : `${startDate} 00:00:00`,
                                endDate: personal.endDate ? `${personal.endDate} 00:00:00` : `${endDate} 00:00:00`,
                                totalDays: totalDays, 
                                privateType: personal.type, 
                                detail: personal.details, 
                                phone: personal.phone,
                                visitRoute: personal.route || "", 
                                relationship: personal.relation || "", 
                                visitedPersonName: personal.visitName || "", 
                                visitType: personal.visitType || "", 
                                registeredAddress: personal.visitAddress || "", 
                                maritalStatus: personal.maritalStatus || "",
                                birthCount: personal.parity || "", 
                                multipleBirth: personal.multiple || "", 
                                difficultBirth: personal.dystocia || "", 
                            }
                            
                            if (isEditMode && personal.id !== undefined && personal.id !== "") {
                                await ReasonFormApi.updateReasonForm(reasonFormData)
                            } else {
                                await ReasonFormApi.createReasonForm(reasonFormData)
                            }
                        }
                    }
                }

                // 处理学术事由
                if (formData.academicItems?.length > 0) {
                    for (const academic of formData.academicItems) {
                        if (academic.meetingName && academic.organizer) {
                            const reasonFormData = {
                                id: academic.id || "",
                                leaveRegisterId: leaveRegisterId,
                                type: 5, // 学术事由
                                startDate: academic.startDate ? `${academic.startDate} 00:00:00` : `${startDate} 00:00:00`,
                                endDate: academic.endDate ? `${academic.endDate} 00:00:00` : `${endDate} 00:00:00`,
                                subject: academic.meetingName,
                                unit: academic.organizer, 
                                meetingNature: academic.nature || "", 
                                reportType: academic.hasReport || "", 
                                reportTitle: academic.hasReport === '1' ? academic.reportTitle || "" : "", // 如果有报告，则保存报告题目
                                reportPaperCount: academic.academicPaperCount || 0, 
                            }
                            
                            if (isEditMode && academic.id !== undefined && academic.id !== "") {
                                await ReasonFormApi.updateReasonForm(reasonFormData)
                            } else {
                                await ReasonFormApi.createReasonForm(reasonFormData)
                            }
                        }
                    }
                }

                // 处理其他事由
                if (formData.otherItems?.length > 0) {
                    for (const other of formData.otherItems) {
                        if (other.description) {
                            const reasonFormData = {
                                id: other.id || "",
                                leaveRegisterId: leaveRegisterId,
                                type: 6, // 其他事由
                                detail: other.description, 
                            }
                            
                            if (isEditMode && other.id !== undefined && other.id !== "") {
                                await ReasonFormApi.updateReasonForm(reasonFormData)
                            } else {
                                await ReasonFormApi.createReasonForm(reasonFormData)
                            }
                        }
                    }
                }
            }
            return true
        } catch (error) {
            console.error('提交失败:', error)
            Alert.alert(
                '提交失败', 
                '请假申请提交失败，请检查网络连接后重试。\n\n错误信息：' + (error instanceof Error ? error.message : '未知错误'),
                [
                    { text: '重试', onPress: () => submitLeaveApplication(formData) },
                    { text: '取消', style: 'cancel' }
                ]
            )
            return false
        } finally {
            setIsSubmitting(false)
        }
    }, [selectedReasons, startDate, endDate, mainLeaveData, onSave, getDictOptions, saveDataToStorage, isEditMode, editData, validateFormData])

    return {
        isSubmitting,
        validateFormData,
        submitLeaveApplication
    }
}
